package nil.ed.simulator.request.biz.qq.activity;

import lombok.extern.slf4j.Slf4j;
import nil.ed.simulator.request.client.JsFunc;
import nil.ed.simulator.request.client.activity.AbstractHttpActivity;
import nil.ed.simulator.request.enums.ActivityGroup;
import nil.ed.template.FreeMarkerTemplateEngineAdapter;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.openjdk.nashorn.api.scripting.AbstractJSObject;

import javax.script.ScriptException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * App Index 活动.
 * @author lidelin.
 */
@Slf4j
public class Seq005FinalLoginActivity extends AbstractHttpActivity {

    private static final String LOGIN_URL = "https://ssl.ptlogin2.qq.com/login?u=%s&verifycode=%s&pt_vcode_v1=0&pt_verifysession_v1=%s&p=%s&pt_randsalt=2&u1=https://aq.qq.com/cn2/manage/mbtoken/app_index&ptredirect=1&h=1&t=1&g=1&from_ui=1&ptlang=2052&action=1-17-1646839166318&js_ver=22030810&js_type=1&login_sig=%s&pt_uistyle=40&aid=2001601&ptdrvs=%s&sid=%s&=";

    @Override
    protected HttpUriRequest getRequest(Map<String, Object> attrMap) {
        try {
            attrMap.put("encrypt_password", getEncryption(attrMap));
            String loginTemplate = String.format(LOGIN_URL, "${qq}", "${checkVC_code}", "${checkVC_verifysession}", "${encrypt_password}", "${cookie_pt_login_sig}", "${checkVC_ptdrvs}", "${checkVC_sessionID}");
            String finalUrl = FreeMarkerTemplateEngineAdapter.INSTANCE.process(loginTemplate, attrMap);
            log.info("qq = {} login url = {}", attrMap.get("qq"), finalUrl);
            return new HttpGet(finalUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected boolean doFinalProcess(HttpResponse response, Map<String, Object> customAttrMap) {
        try {
            String content = String.join("\n", IOUtils.readLines(response.getEntity().getContent(), StandardCharsets.UTF_8));
            customAttrMap.put("login.message", content);
            log.info("qq = {} login content = {}", customAttrMap.get("qq"), content);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public ActivityGroup getGroup() {
        return ActivityGroup.QQ_LOGIN;
    }

    @Override
    public int getSort() {
        return 30;
    }

    static String getEncryption(Map<String, Object> attrMap) throws ScriptException, NoSuchMethodException {
        AbstractJSObject object = (AbstractJSObject) JsFunc.JS_ENGINE.get("e");
        return (String) JsFunc.JS_ENGINE.invokeMethod(object.getMember("default"), "getEncryption", attrMap.getOrDefault("password", ""), attrMap.getOrDefault("checkVC_salt", ""), attrMap.getOrDefault("checkVC_code", ""), false);
    }
}
